package com.yksj.healthtalk.ui.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.universalimageloader.core.ImageLoader;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.comm.ImageGalleryActivity;
import com.yksj.healthtalk.comm.ShopPayActivity;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.comm.ZoomImgeDialogFragment;
import com.yksj.healthtalk.entity.ShopListItemEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.views.HorizontalListView;
import com.yksj.healthtalk.utils.StringFormatUtils;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 商品介绍
 * 
 * @author Administrator
 * 
 */
public class ServerCenterDescription extends BaseFragmentActivity implements
		OnClickListener, OnDilaogClickListener {

	private TextView shopContent;
	private int mContentnumPage = 1;
	private ShopListItemEntity entity;
	private LinearLayout mLinearLayout;
	private ImageLoader imageLoader;
	private List<String> listAddress = new ArrayList<String>();
	private MyAdapter myAdapter;
	private HorizontalListView mHorizontalListView;
	private DisplayMetrics metrics;;
	private String senderId;
	private ImageButton shop_button;
	private ViewGroup anim_mask_layout;
	private RequestParams mBuyParams;//加入购物车的参数
	private String merchantID;
	private com.alibaba.fastjson.JSONObject res;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		setContentView(R.layout.server_center_shop_description);
		senderId = getIntent().getStringExtra("id");
		initTitle();
		initView();
		initData(mContentnumPage);
	}

	private void initView() {
		titleLeftBtn.setOnClickListener(this);
		titleTextV.setTextColor(Color.BLACK);
		titleRightBtn.setOnClickListener(this);
		titleRightBtn2.setOnClickListener(this);
		
		titleRightBtn.setVisibility(View.VISIBLE);
		titleRightBtn2.setVisibility(View.VISIBLE);
		
		titleRightBtn2.setBackgroundResource(R.drawable.server_order);
		titleRightBtn.setBackgroundResource(R.drawable.shopping_trolley);
		titleTextV.setText("商品介绍");
		entity = (ShopListItemEntity) getIntent().getSerializableExtra("entity");
		//查看购物车是否有商品
		if (getIntent().hasExtra("haveShoppingCar") ) {
			if (getIntent().getIntExtra("haveShoppingCar", 0) != 0) {
//				shopPointDrawView.showPoint(true);
//				shopPointDrawView.invalidateSelf();
				HTalkApplication.haveShoppingCar = 1;
			}else {
				HTalkApplication.haveShoppingCar = 0;
				
			}
		}
		
//		//查看是否能购买
//		if (entity.getMERCHANT_ID() != null && !entity.getMERCHANT_ID().equals("1")) {
//			titleRightBtn2.setVisibility(View.GONE);
//			titleRightBtn.setVisibility(View.GONE);
//			findViewById(R.id.shop_button).setVisibility(View.GONE);
//		}
		imageLoader = ImageLoader.getInstance();

		mHorizontalListView = (HorizontalListView) findViewById(R.id.galleryDemo);
		myAdapter = new MyAdapter(this);
		mHorizontalListView.setAdapter(myAdapter);
		mHorizontalListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(ServerCenterDescription.this,
						ImageGalleryActivity.class);
				String[] str = new String[] {};
				intent.putExtra(ImageGalleryActivity.URLS_KEY,
						listAddress.toArray(str));
				intent.putExtra("type", 1);
				intent.putExtra("position", position);
				intent.putExtra("title", entity.getGOODS_NAME());
				intent.putExtra(ImageGalleryActivity.TYPE_KEY, 0);// 0,1单个,多个
				startActivity(intent);
			}
		});
		if (listAddress.size() > 1) {
			mHorizontalListView.setSelection(1);
			myAdapter.notifyDataSetChanged();
		}
		TextView shopName = (TextView) findViewById(R.id.name_shop);
		shopName.setText(entity.getGOODS_NAME());
		TextView shopGuiGe = (TextView) findViewById(R.id.guige_shop);
		shopGuiGe.setText("商品规格: " + entity.getSPECIFICATIONS());
		TextView moneyPtong = (TextView) findViewById(R.id.putong_money);
		if(entity.getVIP_PRICE()==null){
			moneyPtong.setText("普通会员: ￥");
		}else{
			moneyPtong.setText("普通会员: ￥" + entity.getVIP_PRICE());
		}
		TextView moneyShiChang = (TextView) findViewById(R.id.shichang_money);
		String price;
		if (TextUtils.isEmpty(entity.getCURRENT_PRICE())) {
			price = entity.getSHOP_PRICE();
		}else {
			price = entity.getCURRENT_PRICE();
		}
		
		if(price==null){
			moneyShiChang.setText("市场价格: ￥");
		}else{
			moneyShiChang.setText("市场价格: ￥" + price);
		}
		
		TextView shopAddress = (TextView) findViewById(R.id.address_money);

		shopContent = (TextView) findViewById(R.id.content);
		shopAddress.setText(entity.getFACTORY());

		mLinearLayout = (LinearLayout) findViewById(R.id.count_images);
		findViewById(R.id.loadButton).setOnClickListener(this);
		shop_button = (ImageButton)findViewById(R.id.shop_button);
		shop_button.setOnClickListener(this);
		findViewById(R.id.buy_button).setOnClickListener(this);
	}
	
	@Override
	protected void onStart() {
		if (HTalkApplication.haveShoppingCar == 1) {
			titleRightBtn.setBackgroundResource(R.drawable.shopping_trolley_sel);
		}else {
			titleRightBtn.setBackgroundResource(R.drawable.shopping_trolley);
		}
		super.onStart();
	}

	private void initData(int num) {// 4410
		HttpRestClient.doHttpServiceDescripTion(senderId, String.valueOf(num),
				entity.getGOODS_ID(), new AsyncHttpResponseHandler(this) {
					@Override
					public void onSuccess(int statusCode, String content) {
						super.onSuccess(statusCode, content);
						try {
							JSONObject object = new JSONObject(content);
							if ("0".equals(object.getString("isnext"))) {
								findViewById(R.id.loadButton).setVisibility(View.GONE);
								if (mContentnumPage != 1)
									ToastUtil.showToastPanl("暂无内容....");
							}
							// 存放图片
							JSONArray jsonArray = object
									.getJSONArray("GOODSPICS");
							listAddress.clear();
							for (int i = 0; i < jsonArray.length(); i++) {
								listAddress.add(jsonArray.getJSONObject(i).getString("PICTURE_ADDR"));
							}
							if (listAddress.size() > 0) {
								findViewById(R.id.defaultpic).setVisibility(View.GONE);
								mHorizontalListView.setVisibility(View.VISIBLE);
								myAdapter.notifyDataSetChanged();
							}
							JSONArray array = object
									.getJSONArray("DESCRIPTION");
							JSONObject jsonObject = array.getJSONObject(0);
							String flage = jsonObject
									.getString("DESCRIPTION_TYPE");
							if ("10".equals(flage))// 文字
								shopContent.setText(shopContent.getText()
										.toString()
										+ array.getJSONObject(0).getString(
												"DESCRIPTION"));
							else {// 图片
								findViewById(R.id.loadButton).setVisibility(
										View.GONE);
								LinearLayout layout = new LinearLayout(
										ServerCenterDescription.this);
								layout.setGravity(Gravity.CENTER_HORIZONTAL);
								layout.setOrientation(LinearLayout.VERTICAL);
								for (int i = 0; i < array.length(); i++) {
									ImageView imageViewContent = new ImageView(
											ServerCenterDescription.this);
									imageViewContent
											.setLayoutParams(new LayoutParams(
													metrics.widthPixels / 2,
													metrics.widthPixels / 2));
									imageViewContent
											.setScaleType(ScaleType.FIT_XY);
									JSONObject obj = (JSONObject) array.get(i);
									final String address = obj
											.getString("DESCRIPTION");// http://a1.att.hudong.com/21/04/01300000350658125178048481924.jpg
									imageLoader.displayImage(address,
											imageViewContent);
									layout.addView(imageViewContent);
									imageViewContent
											.setOnClickListener(new OnClickListener() {
												@Override
												public void onClick(View v) {
													ZoomImgeDialogFragment.show(address,getSupportFragmentManager());
												}
											});
								}
								mLinearLayout.addView(layout);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.title_right2:
				intent = new Intent(getApplicationContext(),ServerCenterOrderListActivity.class);
				intent.putExtra("merchant_id", entity.getMERCHANT_ID());
				startActivity(intent);
			break;
		case R.id.title_right:
				HttpRestClient.doHttpCartList(entity.getMERCHANT_ID(),new TtrolleyHandler(2));
			break;
		case R.id.title_back:
			finish();
			break;
		case R.id.loadButton:
			mContentnumPage++;
			initData(mContentnumPage);
			break;
		case R.id.shop_button:
				HttpRestClient.doHttpAddCart(StringFormatUtils.getGoodsInfoStr(entity),entity.getMERCHANT_ID(),new TtrolleyHandler(1));
			break;
		case R.id.buy_button:
				HttpRestClient.doHttpBuyMedicine(entity.getMERCHANT_ID(), entity.getGOODS_ID(), new JsonsfHttpResponseHandler(this){
					@Override
					public void onSuccess(int statusCode,
							com.alibaba.fastjson.JSONObject response) {
						 if(response.containsKey("SUPPORT_BUY")){
							if(response.getIntValue("SUPPORT_BUY") == 0){
								if (response.containsKey("info")) { 
									SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  response.getString("info"));
								}else {
									SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),"该商品已下架,暂不支持购买");
								}
							}else if (response.containsKey("SHELVES_FLAG")) {
								String SHELVES_FLAG = response.getString("SHELVES_FLAG");
								if (!TextUtils.isEmpty(SHELVES_FLAG) && SHELVES_FLAG.equals("1")) {
									//特殊商品提示
										RequestParams params = new  RequestParams();
										params.put("merchantID", response.getString("merchantID"));
										params.put("customerID", SmartFoxClient.getLoginUserId());
										params.put("sec", SmartFoxClient.getLoginUserId()+response.getString("sec"));
										params.put("cartID", response.getString("cartID"));
										params.put("askTime", response.getString("askTime"));
										params.put("addr",  response.getString("addr"));
										params.put("username", response.getString("username"));
										ArrayList<HashMap<String, Integer>> value = new ArrayList<HashMap<String,Integer>>();
										HashMap<String, Integer> map = new HashMap<String, Integer>();
										map.put("goods_id", Integer.valueOf(entity.getGOODS_ID()));
										map.put("goods_number", 1);
										value.add(map);
										merchantID = response.getString("merchantID");
										params.put("goodsInfo", com.alibaba.fastjson.JSONArray.toJSONString(value));
										mBuyParams = params;
										res = response;
										if (response.getString("specialFlag").equals("")) {
											HttpRestClient.doHttpTimeStep(merchantID, "10");
											Intent intent2 = new Intent(getApplicationContext(), ShopPayActivity.class);
											intent2.putExtra("url", mBuyParams.toString());
											intent2.putExtra("merchantId", merchantID);
											intent2.putExtra("addr",res.getString("addr"));
											HttpRestClient.doHttpTimeStep(merchantID, "10");
											startActivity(intent2);
										}else {
											DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(), response.getString("specialFlag"), "取消", "确定", ServerCenterDescription.this);
										}
								}else {
									if (response.containsKey("info")) {
										SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), response.getString("info"));
									}else {
										SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  "该商品已下架,暂不支持购买");
									}
									
								}
							}
						}
							
						super.onSuccess(statusCode, response);
					}
					
					@Override
					public void onFailure(Throwable error, String content) {
						super.onFailure(error, content);
					}
				});
			break;
		/*
		 * case R.id.shop_icon: if (entity.getPICTURE_ADDR() == null||
		 * "null".equals(entity.getPICTURE_ADDR())) { return; } Intent intent =
		 * new Intent(this,ImageGalleryActivity.class);
		 * intent.putExtra(ImageGalleryActivity.URLS_KEY,new
		 * String[]{entity.getPICTURE_ADDR()});
		 * intent.putExtra(ImageGalleryActivity.TYPE_KEY,0);//0,1单个,多个
		 * intent.putExtra("type", 1); startActivity(intent); break;
		 */
		}

	}

	class MyAdapter extends BaseAdapter {

		private final LayoutInflater inflater;

		public MyAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return listAddress.size();
		}

		@Override
		public Object getItem(int position) {
			return listAddress.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				convertView = inflater.inflate(R.layout.image_layout, null);
			}
			ImageView imageView = (ImageView) convertView
					.findViewById(R.id.imagelayoutParams);
			// imageView.setLayoutParams(new
			// LinearLayout.LayoutParams(metrics.widthPixels/2,metrics.widthPixels/2));
			// imageView.setScaleType(ScaleType.FIT_XY);
			imageLoader.displayImage(listAddress.get(position).toString(),
					imageView);
			return convertView;
		}

	}

	class TtrolleyHandler extends JsonHttpResponseHandler {
		int type; // 1加入购物车 2查询购物车列表
		private ImageView buyImg;

		public TtrolleyHandler(int type) {
			super(ServerCenterDescription.this);
			this.type = type;
		}

		@Override
		public void onSuccess(int statusCode, JSONObject response) {
			// if (type == 1) {//加入购物
			if (type == 1 && response != null && !response.has("error_message")) {
				titleRightBtn.setBackgroundResource(R.drawable.shopping_trolley_sel);
				HTalkApplication.haveShoppingCar = 1;
				int[] start_location = new int[2];// 一个整型数组，用来存储按钮的在屏幕的X、Y坐标
				shop_button.getLocationInWindow(start_location);// 这是获取购买按钮的在屏幕的X、Y坐标（这也是动画开始的坐标）
				buyImg = new ImageView(ServerCenterDescription.this);// buyImg是动画的图片，我的是一个小球（R.drawable.sign）
				buyImg.setImageResource(R.drawable.medic_move);// 设置buyImg的图片
				setAnim(buyImg, start_location);// 开始执行动画
				return;
			} 
			try {
				if (response.has("info")) { 
					ToastUtil.showToastPanl(response.getString("info"));
				} else if (response.has("money")) {
					Intent intent = new Intent(getApplicationContext(),
							ServerCenterTrolleyActivity.class);
					intent.putExtra("MERCHANT_ID", entity.getMERCHANT_ID());
					intent.putExtra("response", response.toString());
					startActivityForResult(intent, 1);
//					{}
				}else {
					Intent intent = new Intent(getApplicationContext(),ServerCenterTrolleyActivity.class);
					intent.putExtra("MERCHANT_ID", entity.getMERCHANT_ID());
					startActivity(intent);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			super.onSuccess(statusCode, response);
		}

		@Override
		public void onSuccess(int statusCode, JSONArray response) {
			Intent intent = new Intent(getApplicationContext(),ServerCenterTrolleyActivity.class);
			startActivity(intent);
			super.onSuccess(statusCode, response);
		}
	}
	
	
	private void setAnim(final View v, int[] start_location) {
		anim_mask_layout = null;
		anim_mask_layout = createAnimLayout();
		anim_mask_layout.addView(v);//把动画小球添加到动画层
		final View view = addViewToAnimLayout(anim_mask_layout, v,
				start_location);
		int[] end_location = new int[2];// 这是用来存储动画结束位置的X、Y坐标
		titleRightBtn.getLocationInWindow(end_location);// shopCart是那个购物车

		// 计算位移
		int endX = end_location[0] - start_location[0];// 动画位移的X坐标
		int endY = end_location[1] - start_location[1];// 动画位移的y坐标
		
//		ScaleAnimation mScaleAnimation = new ScaleAnimation(0,
//				endX, 0, 0);
//		mScaleAnimation.setInterpolator(new LinearInterpolator());
//		translateAnimationX.setRepeatCount(0);// 动画重复执行的次数
//		translateAnimationX.setFillAfter(true);
		 
		ScaleAnimation animation =new ScaleAnimation(1f, 0f, 1f, 0f,Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,0.5f);
		animation.setInterpolator(new LinearInterpolator());
		animation.setRepeatCount(0);// 动画重复执行的次数
		animation.setFillAfter(true);
		
		TranslateAnimation translateAnimationX = new TranslateAnimation(0,
				endX, 0, 0);
		translateAnimationX.setInterpolator(new AccelerateInterpolator());
		translateAnimationX.setRepeatCount(0);// 动画重复执行的次数
		translateAnimationX.setFillAfter(true);

		TranslateAnimation translateAnimationY = new TranslateAnimation(0, 0,
				0, endY);
		translateAnimationY.setInterpolator(new DecelerateInterpolator());
		translateAnimationY.setRepeatCount(0);// 动画重复执行的次数
		translateAnimationX.setFillAfter(true);

		AnimationSet set = new AnimationSet(false);
		set.setFillAfter(false);
		set.addAnimation(animation);
		set.addAnimation(translateAnimationX);
		set.addAnimation(translateAnimationY);
		
		
		set.setDuration(1000);// 动画的执行时间
		view.startAnimation(set);
		// 动画监听事件
		set.setAnimationListener(new AnimationListener() {
			// 动画的开始
			@Override
			public void onAnimationStart(Animation animation) {
				v.setVisibility(View.VISIBLE);
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
			}

			// 动画的结束
			@Override
			public void onAnimationEnd(Animation animation) {
				v.setVisibility(View.GONE);
				RotateAnimation animation2 = new RotateAnimation(90, -90, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
				animation2.setDuration(500);
				titleRightBtn.startAnimation(animation2);
			}
		});

	}
	
	
	/**
	 * @Description: 创建动画层
	 * @param
	 * @return void
	 * @throws
	 */
	private ViewGroup createAnimLayout() {
		ViewGroup rootView = (ViewGroup) this.getWindow().getDecorView();
		LinearLayout animLayout = new LinearLayout(this);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);
		animLayout.setLayoutParams(lp);
		animLayout.setId(Integer.MAX_VALUE);
		animLayout.setBackgroundResource(android.R.color.transparent);
		rootView.addView(animLayout);
		return animLayout;
	}
	
	private View addViewToAnimLayout(final ViewGroup vg, final View view,
			int[] location) {
		int x = location[0];
		int y = location[1];
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		lp.leftMargin = x;
		lp.topMargin = y;
		view.setLayoutParams(lp);
		return view;
	}

	@Override
	public void onDismiss(DialogFragment fragment) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onClick(DialogFragment fragment, View v) {
		HttpRestClient.doHttpTimeStep(merchantID, "10");
		Intent intent2 = new Intent(getApplicationContext(), ShopPayActivity.class);
		intent2.putExtra("merchantId", merchantID);
		intent2.putExtra("url", mBuyParams.toString());
		intent2.putExtra("addr",res.getString("addr"));
		startActivity(intent2);
	}
	
}
